<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="setColStyle" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.model == 'workFlowStatus'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) of arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.value }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.key"
                  :key="c_item.key"
                ) {{ c_item.value }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-100(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-100(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计：
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |应付金额：
              span.text-info.pl-5.pr-5.font-weight {{tableComone.total}}
              |元
            .pull-right.table-title-btns
              //- Button.mr-10(type="info" @click="handleShowBatchImportModal") 导入发放结果
              //- Button.mr-10(type="info" @click="handleShowChooseBankModal") 导出发放表
              Button.mr-10(v-if="hasExportAll" type="info" @click="handleExport") 导出
              Button(v-if="hasExportAllDetails" type="info" @click="handleExportAllDetails") 导出明细
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasPaied" type="text" @click="handleShowSendConfirmModal(row)") 确认发放
            Button.mr-10(v-if="hasGetDetails" type="text" @click="goDetail(row)") 明细
            Button.mr-10(v-if="hasReject" type="text" :disabled="row.status!=2" @click="handleShowSendBackModal(row, 4)") 驳回
            Button.mr-10(v-if="hasBack" type="text" :disabled="row.status!=3" @click="handleShowSendBackModal(row, 5)") 退回

    //- 导入弹窗
    BatchImportModal(ref="BatchImportModal" @query="searchFn")
    //- 退回弹窗
    SendBackModal(ref="SendBackModal" @query="searchFn")
    //- 退回弹窗
    ChooseBankModal(ref="ChooseBankModal" @query="searchFn")
    //- 确认弹窗
    SendConfirmModal(ref="SendConfirmModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinanceSPayableApi } from "@/api/FinanceSPayable.api.js"
import { OrganizationBankApi } from "@/api/OrganizationBank.api.js"
import { SalaryThead } from "./tableHead.js"
import _cloneDeep from "clone-deep"
import { EmployeesApi } from "@/api/Employees.api.js"
import BatchImportModal from "./modal/BatchImportModal.vue"
import SendBackModal from "./modal/SendBackModal.vue"
import SendConfirmModal from "./modal/SendConfirmModal.vue"
import ChooseBankModal from "./modal/ChooseBankModal.vue"
import dataApi from '@/api/data.js'
const style = "ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8"
export default {
  name: "sPayableList",

  components: {
    BatchImportModal,
    SendBackModal,
    ChooseBankModal,
    SendConfirmModal
  },

  data() {
    return {
      // companyId: "", // 公司ID
      // companyName: "", // 公司名称
      // employeeId: "", // 员工ID
      thead: _cloneDeep(SalaryThead),
      tableData: [],
      formData: {
        companyName: null,
        status: null,
        startDate: new Date(),
        endDate: new Date(),
        workFlowStatus: null
      },
      formItem: [
        { type: "input", label: "客户名称：", placeholder: "请输入客户名称", prop: "companyName", model: "companyName", style: "ivu-col-span-8" },
        { type: 'select', label: '状态：', placeholder: '请输入状态', prop: 'status', model: 'status', options: 'statusOps', style: 'ivu-col-span-8' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'startDate', model1: 'startDate', placeholder2: '结束日期', prop2: 'endDate', model2: 'endDate', style: 'ivu-col-span-8' },
        { type: 'select', label: '审批结果：', placeholder: '请选择审批结果', prop: 'workFlowStatus', model: 'workFlowStatus', options: 'workflowstatus', style: 'ivu-col-span-8' },
        { type: 'button', style: 'ivu-col-span-2' }
      ],
      rules: {},
      selectedId: [], // 勾选的id集合,array格式
      selectedArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 合计
      },
      downLoadRul: "",
      arrListDown: {
        statusOps: [
          // {label: '待申请', value: '1'},
          // // {label: '已申请', value: '2'},
          // {label: '已付款', value: '3'},
          // {label: '待付款', value: '4'},
          // {label: '已驳回', value: '-1'},
          // {label: '已退回', value: '-2'}
        ],
        bankList: [],
        workflowstatus: []
      },
      datePickerDefault: new Date(), // 当前时间
    };
  },

  watch: {},

  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    setFormItem () {
      if (this.isWorkFlow) {
        return this.formItem
      } else {
        return [...this.formItem.slice(0, 3), ...this.formItem.slice(4, this.formItem.length + 1)]
      }
    },

    setColStyle () {
      if (this.isWorkFlow) {
        return 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-8'
      } else {
        return 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6'
      }
    },

    actionArr() {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code;
      });
      return arr;
    },
    // 个税付款确认
    hasToPostIncome() {
      return this.actionArr.indexOf("ToPostIncome") > -1;
    },
    // 导出
    hasExportAll() {
      return this.actionArr.indexOf("ExportAll") > -1;
    },
    // 导出明细
    hasExportAllDetails() {
      return this.actionArr.indexOf("ExportAllDetails") > -1;
    },
    // 退回
    hasBack() {
      return this.actionArr.indexOf("Back") > -1;
    },
    // 驳回
    hasReject() {
      return this.actionArr.indexOf("Reject") > -1;
    },
    // 明细
    hasGetDetails() {
      return this.actionArr.indexOf("GetDetails") > -1;
    },
    // 导出明细
    hasExportApplyDetail() {
      return this.actionArr.indexOf("ExportApplyDetail") > -1;
    },
    // 导入发放结果
    hasImportResult() {
      return this.actionArr.indexOf("ImportResult") > -1;
    },
    // 导出发放表
    hasExportGrantData() {
      return this.actionArr.indexOf("ExportGrantData") > -1;
    },
    // 确认发放
    hasPaied() {
      return this.actionArr.indexOf("Paied") > -1;
    },
  },

  
  mounted() {
    this.getEnum()
    this.queryBankList()
    this.query()
    // setTimeout(() => {
    //     console.log('this.arrListDown.status: ', this.arrListDown.status)
    //     this.arrListDown.status.map((item, index) => {
    //       if (item.label == '待申请') {
    //         this.arrListDown.status.splice(index, 1 )
    //       }
    //     })
    //     console.log('this.arrListDown.status: ', this.arrListDown.status)
    // }, 100);
  },

  methods: {
    // 获取下拉
    async getEnum () {
      let groupNames = 'financesalary.status,finance.workflowstatus'
      let res = await dataApi.getEnum({
        groupName: groupNames
      })
      this.arrListDown.statusOps = this.getItems(res.data, 'financesalary.status')
      this.arrListDown.workflowstatus = this.getItems(res.data, 'finance.workflowstatus')
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },
    // 搜索
    searchFn() {
      this.tableComone.pageIndex = 1;
      this.query();
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage(val) {
      this.tableComone.pageIndex = val;
      this.query();
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange(val) {
      this.tableComone.pageIndex = 1;
      this.tableComone.pageSize = val;
      this.query();
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
      };
      let res = await FinanceSPayableApi.getSList(params);
      console.log("列表res: ", res);
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data;
        this.tableComone.totalRows = res.data.totalRows;
        this.tableComone.total = res.data.total;
        this.tableComone.salaryTotal = res.data.salaryTotal;
        this.tableComone.incomeTotal = res.data.incomeTotal;
      } else {
        this.tableData = [];
      }
      this.loading = false;
    },

    // 表格选择操作
    handleOnSelectChange(value) {
      this.selectedArr = value.map(item => {
        return { id: item.id, name: item.name };
      });
      this.selectedId = value.map(item => {
        return item.id;
      });
      console.log("列表勾选数组1", this.selectedArr);
      console.log("列表勾选数组2", this.selectedId);
    },

    // 获取银行下拉
    async queryBankList () {
      var params = {
        HasPaging: true,
        PageIndex: 1,
        PageSize: 100
      }
      let res = await OrganizationBankApi.getList(params)
      console.log('获取银行下拉res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.bankList = res.data.data.map(item => {return {label: item.bankName, value: item.bankName}})
      } else {
        this.arrListDown.bankList = []
      }
      this.loading = false
    },

    // 日期选择
    handleChangeDatePicker(val) {
      console.log("val: ", val);
    },

    // 导出薪资应付账单
    async handleExport() {
      var params = {
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
        salaryIDs: this.selectedId
      };
      let res = await FinanceSPayableApi.export(params);
      console.log("导出薪资应付账单res: ", res);
      if (res.status === 200 && res.data.success) {
        console.log("返回链接: ", res.data.message);
        window.open(baseUrl + res.data.message, "_blank");
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        });
      }
    },

    // 导出明细
    async handleExportAllDetails() {
      var params = {
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        startDate: this.formData.startDate ? this.$moment(this.formData.startDate).format('YYYY-MM'):'',
        endDate: this.formData.endDate ? this.$moment(this.formData.endDate).format('YYYY-MM'):'',
        salaryIDs: this.selectedId
      };
      let res = await FinanceSPayableApi.exportAllDetails(params);
      console.log("导出明细res: ", res);
      if (res.status === 200 && res.data.success) {
        console.log("返回链接: ", res.data.message);
        window.open(baseUrl + res.data.message, "_blank");
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        });
      }
    },

    // 去详情
    goDetail (row) {
      console.log('去详情',row)
      this.$router.push({
        path: '/sPayableDetail',
        name: 'sPayableDetail',
        query: {
          salaryID: row.id,
          companyID: row.customerGUID,
          customerName: row.customerName,
          legalName: row.legalName,
          salaryMonth: row.salaryMonth,
        }
      })
    },

    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.show()
    },

    handleShowSendBackModal (row, backType) {
      this.$refs.SendBackModal.modalKey = 'fromList'
      this.$refs.SendBackModal.show(row, this.selectedId,backType)
    },

    handleShowSendConfirmModal (row) {
      this.$refs.SendConfirmModal.modalKey = 'fromList'
      this.$refs.SendConfirmModal.show(row, this.selectedId)
    },

    handleShowChooseBankModal () {
      this.$refs.ChooseBankModal.arrListDown = this.arrListDown
      this.$refs.ChooseBankModal.show()
    },

    // 是否发放前询问
    isPaiedModal (row) {
      this.$Modal.confirm({
        title: '是否确认发放',
        onOk: () => {
          this.handlePaied(row)
        }
      })
    },

    // 确认发放
    async handlePaied (row) {
      var params = {
        SalaryID: row.id,
        SalaryMonth: row.salaryMonth
      }
      let res = await FinanceSPayableApi.paied(params)
      console.log('确认发放res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query();
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    }
  } // methods end
}
</script>

<style lang="less" scoped>
</style>
